# -*- coding: utf-8 -*-

# @Time : 2020/3/17 11:22
# @Author : WYT
# @Site :
# @File : UploadAccessory.py
# @Software: PyCharm
import datetime
import json
import os
import re

from lxml import etree

from PageObjectRequests import base_url
from settings import web_type
from util import http_utils
from util.DataQuery.DbTools import DbTools
from util.g import g
from util.pdfSplit.compress_pdf import CompressPdf
from util.pdfSplit.pdf_split import get_file_oss
from util.pdfSplit.pdf_to_image import pdf_to_image
from util.selenium.webdriver.common.by import By

from base.BaseMethod import BM
from util.DataQuery.FormDataDecorator import CheckProcess


class UploadAccessory():
    btn_loc = (By.LINK_TEXT, "上传附件")
    current_year = datetime.datetime.now().year
    content_iframe_loc = (By.CSS_SELECTOR, "#innocomFrame")
    buslic_loc = (By.XPATH, "//div[@class='box-body']/div[1]/div[@class='main']//a")
    farpt3_loc = (By.XPATH, "//div[@class='box-body']/div[3]/div[contains(string(), '{}')]//a".format(
        current_year - 3))
    farpt2_loc = (By.XPATH, "//div[@class='box-body']/div[3]/div[contains(string(), '{}')]//a".format(
        current_year - 2))
    farpt1_loc = (By.XPATH, "//div[@class='box-body']/div[3]/div[contains(string(), '{}')]//a".format(
        current_year - 1))
    psrpt_loc = (By.XPATH, "//div[@class='box-body']/div[4]//a")
    raxrtn3_loc = (By.XPATH, "//div[@class='box-body']/div[5]/div[contains(string(), '{}')]//a".format(
        current_year - 3))
    raxrtn2_loc = (By.XPATH, "//div[@class='box-body']/div[5]/div[contains(string(), '{}')]//a".format(
        current_year - 2))
    raxrtn1_loc = (By.XPATH, "//div[@class='box-body']/div[5]/div[contains(string(), '{}')]//a".format(
        current_year - 1))
    rdcostrptr_loc = (By.XPATH, "//div[@class='box-body']/div[6]//a")
    otheratt_loc = (By.XPATH, "//div[@class='box-body']/div[7]//a")
    tree = None

    def __init__(self, driver=None):
        self.driver = driver

    @property
    def class_name(self):
        return self.__class__.__name__

    def upload(self, upload_url, data, a_ele, file_path, res_type, year=None, size=4):
        if not BM.check_file(file_path, size=size):
            rule_id = BM.get_rule_id(res_type=res_type, year=year)
            sql = """
            select * from ent_res_pdf where co_id={} and `year`={} and rule_id={} and web_type='{}'
            """.format(g.co_id, g.year, rule_id, web_type)
            file_data = DbTools.get_hitech_record_by_sql(sql=sql)
            if not file_data or not file_data.get("oss_path"):
                return
            oss_path = file_data.get("oss_path")
            if res_type != "buslic":
                oss_file = get_file_oss(oss_path=oss_path, local_path=file_path + ".pdf")
                BM.wait_file(file_path=oss_file)
                CompressPdf(file_path=oss_file, max_size=size).compress()
                BM.wait_file(file_path=file_path)
            else:
                pdf_to_image(imagePath=os.path.split(file_path)[0], filename=res_type, size=0.48, filePath=file_path)
                BM.wait_file(file_path=file_path)
        onclick = a_ele.attrib.get("onclick")
        href = a_ele.attrib.get("href")
        if "javascript:void(0);" not in href:
            g.logger.info("附件已上传: {}".format(file_path))
            return True
        a_id_pattern = ".*?'(.*?)'.*?"
        a_id_res = re.findall(a_id_pattern, onclick)
        a_id = BM.get_first(a_id_res)
        onchange = BM.get_first(self.tree.xpath("//input[@id='{}']/@onchange".format(a_id)))
        onchange = onchange.replace("handleFile(this,", "").replace(")", "").replace("'", "").replace("\"", "")
        # data_id_res = re.findall(".*?'((?=.*[a-zA-Z])(?=.*[0-9])[A-Za-z0-9].*?)'.*?", onchange)
        data["dataId"] = BM.get_first(onchange.split(",")[0].strip())
        # type_res = re.findall(".*?,'(\d+)',.*?", onchange)
        data["type"] = BM.get_first(onchange.split(",")[1].strip())
        # sub_type_res = re.findall(".*?,'(\d+[_]+\d+)'", onchange)
        data["subType"] = BM.get_first(onchange.split(",")[2].strip())
        res = http_utils.send_post(url=upload_url, data=data, file_path=file_path, file_key="upload", driver=self.driver)
        text = res.get("text")
        text_j = json.loads(text)
        id_str = text_j.get("id")
        if id_str:
            g.logger.info("附件上传成功: {}".format(file_path))
            return True
        else:
            g.logger.info("附件上传失败: {}".format(file_path))
            return False

    @CheckProcess
    def main(self):
        try:
            if not g.need_file:
                return True
            ele = BM.get_ele(driver=self.driver, ele_loc=self.btn_loc)
            detail_url = ele.get_attribute("href")
            # BM.click(driver=self.driver, ele_loc=self.btn_loc)
            if not g.all_optimized:
                BM.switch_to_frame(driver=self.driver, ele_loc=self.content_iframe_loc)
            BM.get_cookie(driver=self.driver)
            detail_url = detail_url if detail_url.startswith("https://") else \
                base_url + (detail_url if detail_url.startswith("/") else "/" + detail_url)
            res = http_utils.send_get(detail_url, driver=self.driver)
            text = res.get("text")
            tree = etree.HTML(text)
            self.tree = tree
            upload_url = "https://gqqy.chinatorch.org.cn/xonlinereport/inforeport/File/upload.do"
            post_data = {
                "dataId": "",
                "type": "",
                "subType": ""
            }
            # 营业执照
            material_path = BM.get_material_path()
            buslic_res = BM.get_first(tree.xpath(self.buslic_loc[1]))
            is_buslic = self.upload(upload_url, post_data, buslic_res, material_path + "\\buslic.png",
                                    "buslic", size=0.5)

            sql = """select creditcode, agency_name, hp_creditcode, hp_agency_name, financial_statements 
            from ent_res_agency where co_id={co_id} and year={year}""".format(co_id=g.co_id, year=g.year)
            data = DbTools.get_hitech_record_by_sql(sql=sql)
            financial_statements = data.get("financial_statements")
            thr_data = json.loads(financial_statements)

            # 近三年财务审计报告
            is_farpt3 = True
            if thr_data.get("nearThrFSCreditcode"):
                post_data["auditDeptCorCode"] = thr_data.get("nearThrFSCreditcode")
                post_data["auditDeptName"] = thr_data.get("nearThrFSName")
                farpt3_res = BM.get_first(tree.xpath(self.farpt3_loc[1]))
                farpt3_year = self.current_year - 3
                is_farpt3 = self.upload(
                    upload_url, post_data, farpt3_res, material_path + "\\FARPT\\farpt_{}.pdf".format(farpt3_year),
                    "farpt", year=farpt3_year, size=8)
                del post_data["auditDeptCorCode"]
                del post_data["auditDeptName"]
            is_farpt2 = True
            if thr_data.get("nearTwoFSCreditcode"):
                post_data["auditDeptCorCode"] = thr_data.get("nearTwoFSCreditcode")
                post_data["auditDeptName"] = thr_data.get("nearTwoFSName")
                farpt2_res = BM.get_first(tree.xpath(self.farpt2_loc[1]))
                farpt2_year = self.current_year - 2
                is_farpt2 = self.upload(
                    upload_url, post_data, farpt2_res, material_path + "\\FARPT\\farpt_{}.pdf".format(farpt2_year),
                    "farpt", year=farpt2_year, size=8)
                del post_data["auditDeptCorCode"]
                del post_data["auditDeptName"]
            is_farpt1 = True
            if thr_data.get("nearOneFSCreditcode"):
                post_data["auditDeptCorCode"] = thr_data.get("nearOneFSCreditcode")
                post_data["auditDeptName"] = thr_data.get("nearOneFSName")
                farpt1_res = BM.get_first(tree.xpath(self.farpt1_loc[1]))
                farpt1_year = self.current_year - 1
                is_farpt1 = self.upload(
                    upload_url, post_data, farpt1_res, material_path + "\\FARPT\\farpt_{}.pdf".format(farpt1_year),
                    "farpt", year=farpt1_year, size=8)
                del post_data["auditDeptCorCode"]
                del post_data["auditDeptName"]
            # 近一年高新产品（服务）收入专项审计报告
            is_psrpt = True
            if data.get("hp_creditcode"):
                post_data["auditDeptCorCode"] = data.get("hp_creditcode")
                post_data["auditDeptName"] = data.get("hp_agency_name")
                psrpt_res = BM.get_first(tree.xpath(self.psrpt_loc[1]))
                is_psrpt = self.upload(
                    upload_url, post_data, psrpt_res, material_path + "\\psrpt.pdf", "psrpt", size=2)
                del post_data["auditDeptCorCode"]
                del post_data["auditDeptName"]
            # 近三年企业所得税纳税申报表
            raxrtn3_res = BM.get_first(tree.xpath(self.raxrtn3_loc[1]))
            raxrtn3_year = self.current_year - 3
            is_raxrtn3 = self.upload(
                upload_url, post_data, raxrtn3_res, material_path + "\\RAXRTN\\raxrtn_{}.pdf".format(raxrtn3_year),
                "raxrtn", year=raxrtn3_year, size=3)
            raxrtn2_res = BM.get_first(tree.xpath(self.raxrtn2_loc[1]))
            raxrtn2_year = self.current_year - 2
            is_raxrtn2 = self.upload(
                upload_url, post_data, raxrtn2_res, material_path + "\\RAXRTN\\raxrtn_{}.pdf".format(raxrtn2_year),
                "raxrtn", year=raxrtn2_year, size=3)
            raxrtn1_res = BM.get_first(tree.xpath(self.raxrtn1_loc[1]))
            raxrtn1_year = self.current_year - 1
            is_raxrtn1 = self.upload(
                upload_url, post_data, raxrtn1_res, material_path + "\\RAXRTN\\raxrtn_{}.pdf".format(raxrtn1_year),
                "raxrtn", year=raxrtn1_year, size=3)
            # 近三年研发费用专项审计报告
            is_rdcostrptr = True
            if data.get("creditcode"):
                post_data["auditDeptCorCode"] = data.get("creditcode")
                post_data["auditDeptName"] = data.get("agency_name")
                rdcostrptr_res = BM.get_first(tree.xpath(self.rdcostrptr_loc[1]))
                is_rdcostrptr = self.upload(
                    upload_url, post_data, rdcostrptr_res, material_path + "\\rdcostrptr.pdf", "rdcostrptr", size=2)
                del post_data["auditDeptCorCode"]
                del post_data["auditDeptName"]
            # 认定机构要求上传的其他附件
            otheratt_res = BM.get_first(tree.xpath(self.otheratt_loc[1]))
            is_otheratt = self.upload(upload_url, post_data, otheratt_res, material_path + "\\otheratt.pdf",
                                      "otheratt", size=2)
            return is_buslic and is_farpt3 and is_farpt2 and is_farpt1 and is_psrpt and is_raxrtn3 and is_raxrtn2 \
                    and is_raxrtn1 and is_rdcostrptr and is_otheratt
        except Exception as err:
            err_msg = "{} file:{} lines:{}".format(err, err.__traceback__.tb_frame.f_globals["__file__"],
                                                           err.__traceback__.tb_lineno)
            raise Exception(err_msg)

if __name__ == '__main__':

    a = UploadAccessory(driver=())
# {"nearTwoFSName":"中瑞诚会计师事务所（特殊普通合伙）江苏分所","nearThrFSName":"0","nearThrFSQuality":true,"nearOneFSQuality":true,"nearThrFSCreditcode":"0","nearOneFSName":"中瑞诚会计师事务所（特殊普通合伙）江苏分所","nearTwoFSCreditcode":"91320104MA232JEEXF","nearTwoFSQuality":true,"nearOneFSCreditcode":"91320104MA232JEEXF"}
